package com.byx.chatclient.adapter;

import android.text.TextUtils;
import android.widget.Adapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;

import com.byx.chatclient.R;
import com.byx.chatclient.bean.SimpleUserBean;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.facebook.drawee.view.SimpleDraweeView;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * SelectUserAdapter
 * 创建群聊时选择好友的适配器
 * @author Superb
 * @date 2021/4/26 10:29
 */
public class SelectFriendAdapter extends BaseQuickAdapter<SimpleUserBean, BaseViewHolder> implements Filterable {
    private static final int LAYOUT_RES_ID = R.layout.layout_select_friend_item;
    private OnSelectedChangedListener mOnSelectedListener;
    private Filter mFilter;
    //数据的备份，用于保存筛选前原有的数据
    private List<SimpleUserBean> mBackup = null;

    // TODO: 2021/4/26 实现有输入和无输入两种筛选界面，对应两种不同的bean对象

    public SelectFriendAdapter(@Nullable List<SimpleUserBean> data) {
        super(LAYOUT_RES_ID, data);
        init();
    }

    public SelectFriendAdapter() {
        super(LAYOUT_RES_ID);
        init();
    }

    private void init() {
        mBackup = new ArrayList<>();
        setOnItemClickListener((adapter, view, position) -> {
            CheckBox checkBox = (CheckBox) getViewByPosition(position, R.id.cb_user);
            assert checkBox != null;
            checkBox.setChecked(!checkBox.isChecked());
        });
    }

    @Override
    public void onBindViewHolder(@NotNull BaseViewHolder holder, int position) {
        ((CheckBox) holder.getView(R.id.cb_user)).setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (mOnSelectedListener != null){
                mOnSelectedListener.onSelectedChanged(position,isChecked);
            }
        });
        super.onBindViewHolder(holder, position);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, SimpleUserBean simpleUserBean) {
        ((SimpleDraweeView) baseViewHolder.getViewOrNull(R.id.sdv_avatar)).setImageURI(simpleUserBean.getAvatar());
        baseViewHolder.setText(R.id.tv_nick_name,simpleUserBean.getNickName());
    }

    public void setOnSelectedListener(OnSelectedChangedListener onSelectedListener) {
        this.mOnSelectedListener = onSelectedListener;
    }

    @Override
    public void addData(SimpleUserBean data) {
        mBackup.add(data);
        super.addData(data);
    }

    @Override
    public void addData(int position, SimpleUserBean data) {
        mBackup.add(position, data);
        super.addData(position, data);
    }

    @Override
    public void addData(int position, @NotNull Collection<? extends SimpleUserBean> newData) {
        mBackup.addAll(position,newData);
        super.addData(position, newData);
    }

    @Override
    public void addData(@NotNull Collection<? extends SimpleUserBean> newData) {
        mBackup.addAll(newData);
        super.addData(newData);
    }

    public interface OnSelectedChangedListener {
        /**
         * 选择某一项时触发此方法
         * @param position 索引
         * @param isSelected 是否选中
         */
        void onSelectedChanged(int position,boolean isSelected);
    }

    /**
     * <p>Returns a filter that can be used to constrain data with a filtering
     * pattern.</p>
     *
     * <p>This method is usually implemented by {@link Adapter}
     * classes.</p>
     *
     * @return a filter used to constrain data
     */
    @Override
    public Filter getFilter() {
        if (mFilter == null){
            return new MyFilter();
        }
        return mFilter;
    }

    public class MyFilter extends Filter{

        /**
         * <p>Invoked in a worker thread to filter the data according to the
         * constraint. Subclasses must implement this method to perform the
         * filtering operation. Results computed by the filtering operation
         * must be returned as a {@link FilterResults} that
         * will then be published in the UI thread through
         * {@link #publishResults(CharSequence,
         * FilterResults)}.</p>
         *
         * <p><strong>Contract:</strong> When the constraint is null, the original
         * data must be restored.</p>
         *
         * @param constraint the constraint used to filter the data
         * @return the results of the filtering operation
         * @see #filter(CharSequence, FilterListener)
         * @see #publishResults(CharSequence, FilterResults)
         * @see FilterResults
         */
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults result = new FilterResults();
            List<SimpleUserBean> list;
            if (TextUtils.isEmpty(constraint)) {//当过滤的关键字为空的时候，我们则显示所有的数据
                list = mBackup;
            } else {//否则把符合条件的数据对象添加到集合中
                list = new ArrayList<>();
                for (SimpleUserBean model : mBackup) {
                    if (model.getNickName().contains(constraint)) { //要匹配的item中的view
                        list.add(model);
                    }
                }
            }
            result.values = list; //将得到的集合保存到FilterResults的value变量中
            result.count = list.size();//将集合的大小保存到FilterResults的count变量中
            return result;
        }

        /**
         * <p>Invoked in the UI thread to publish the filtering results in the
         * user interface. Subclasses must implement this method to display the
         * results computed in {@link #performFiltering}.</p>
         *
         * @param constraint the constraint used to filter the data
         * @param results    the results of the filtering operation
         * @see #filter(CharSequence, FilterListener)
         * @see #performFiltering(CharSequence)
         * @see FilterResults
         */
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            setList((List<SimpleUserBean>) results.values);
        }
    }
}
